-- cmd_activate_account
-- Created by chengb Mar/18/2016
-- 激活渠道账号

-- 内部函数声明
local onConnected;
local onConnectFail;

function Operation.cmd_activate_account(account, channel, code)
    -- 去掉头尾空格
    account = AccountM.removeSpace(account);
    code = AccountM.removeSpace(code);

    trace("cmd_activate_account", "渠道(%s)的帐号(%s)请求认证激活码(%s)",
        channel, account, code);

    -- 当前是连接状态
    if Socket.isConnected() then
        trace("cmd_activate_account", "正在连接服务器，请稍候。")
        return;
    end

     _G.accountActivateInfo = {
         ["account"] = account,
         ["channel"] = channel,
         ["code"] = code,
     };

    -- 移除事件的关注
    EventMgr.remove("cmd_activate_account", event.NETWORK_CONNECTED)
    EventMgr.remove("cmd_activate_account", event.NETWORK_DISCONNECTED)

    -- 关注事件
    EventMgr.register("cmd_activate_account", event.NETWORK_CONNECTED, onConnected);
    EventMgr.register("cmd_activate_account", event.NETWORK_DISCONNECTED, onConnectFail);

    -- 在这之前必须已经获取到aaa_ip和aaa_port了
    if not _G["aaa_ip"] then
        error("获取不到aaa_ip");
        return false;
    end

    if not _G["aaa_port"] then
        error("获取不到aaa_port");
        return false;
    end

    -- 连接服务器
    Socket.connect(_G["aaa_ip"], _G["aaa_port"]);

    -- 处理完成
    return true;
end

-- 连接服务器成功后的处理
onConnected = function()
    -- 移除事件的关注
    EventMgr.remove("cmd_activate_account", event.NETWORK_CONNECTED)
    EventMgr.remove("cmd_activate_account", event.NETWORK_DISCONNECTED)

    local v = _G.accountActivateInfo;

    -- 发送auth指令
    Operation.cmd_internal_auth(CFG_TYPE_CONSOLE, v.account, CFG_AAA_LOGIN);

    -- 发送激活账号指令
    trace("cmd_activate_account", "发送激活账号请求");
    Communicate.send("CMD_ACTIVATE_ACCOUNT", v);

    _G.accountActivateInfo = nil;
end

-- 连接失败的处理
onConnectFail = function()
    trace("cmd_activate_account", "连接AAA失败了");

    -- 移除事件的关注
    EventMgr.remove("cmd_activate_account", event.NETWORK_CONNECTED)
    EventMgr.remove("cmd_activate_account", event.NETWORK_DISCONNECTED)
end



